package com.tduck.cloud.form.util;

import cn.hutool.core.util.ObjectUtil;
import com.tduck.cloud.form.entity.UserFormDataEntity;

import java.util.ArrayList;
import java.util.*;

/**
 * @author zhaoling
 * @date 2023年06月08日 11:00
 */
public class JsonContainsUtils {

    public static List<UserFormDataEntity> getJsonContainsAll(String queryData, List<UserFormDataEntity> userFormDataEntity) {
        String[] queryDataList = new String[]{};
        List<UserFormDataEntity> result = new ArrayList<>();
        if (ObjectUtil.isNotNull(queryData) && !"{}".equals(queryData)) {
            queryDataList = queryData.replace("{", "").replace("}", "").split(",");
        }
        if (queryDataList.length > 0) {
            for (UserFormDataEntity formDataEntity : userFormDataEntity) {
                Map<String, Object> maps = formDataEntity.getOriginalData();
                if (ObjectUtil.isNotNull(maps)) {
                    // 新建标志位
                    boolean hasAllData = true;
                    for (String string : queryDataList) {
                        boolean hasData = false;
                        for (Object map : maps.entrySet()) {
                            String json = "\"" + ((Map.Entry) map).getKey() + "\":" + ((Map.Entry) map).getValue();
                            if (json.equals(string)) {
                                hasData = true;
                                break;
                            }
                        }
                        // 如果当前查询项未匹配上数据项，直接中断
                        if (!hasData) {
                            hasAllData = false;
                            break;
                        }
                    }
                    // 如果所有查询项都匹配上了数据项，则将该表单数据加入结果集合
                    if (hasAllData) {
                        result.add(formDataEntity);
                    }
                }
            }
        } else {
            result = userFormDataEntity;
        }
        return result;
    }
}
